package com.ttnet.bo.implemantations;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.StringTokenizer;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.ttnet.bo.FileBo;

@Component
@Scope("prototype")
public class FileBoImpl implements FileBo {

	@Override
	public void writeTxtFile(StringBuffer stringBuffer, String sessionID) throws IOException {
		String file = System.getProperty("user.dir") + "\\" + sessionID + ".txt";
		BufferedWriter out = new BufferedWriter(new FileWriter(file));
		out.write(stringBuffer.toString());
		out.flush();
		out.close();
	}

	@Override
	public StringBuffer readFromDatFile(InputStream inputStream, String startString, String endString, List<String> omitStringList, List<String> ignoreStringList, int columnSize) throws IOException {

		StringBuffer resultStringBuffer = new StringBuffer();
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

		String line;
		boolean write = false;

		while ((line = reader.readLine()) != null) {
			StringTokenizer st = new StringTokenizer(line);
			int tokenCount = 0;
			if (resultStringBuffer.length() > 0)
				resultStringBuffer.append("\n");
			while (st.hasMoreTokens() && (columnSize < 0 || tokenCount < columnSize)) {
				String nextToken = st.nextToken();

				if (nextToken.equals(startString)) {
					write = true;
					break;
				} else if (nextToken.equals(endString)) {
					write = false;
					break;
				} else {
					boolean omit = false, ignore = false;
					for (String omitString : omitStringList) {
						if (nextToken.startsWith(omitString)) {
							omit = true;
							break;
						}
					}
					for (String omitString : ignoreStringList) {
						if (nextToken.startsWith(omitString)) {
							ignore = true;
							continue;
						}
					}
					if (omit)
						break;
					if (ignore)
						continue;
				}

				if (write) {
					resultStringBuffer.append(nextToken);
					resultStringBuffer.append(" ");

				}
				tokenCount++;
			}

		}

		reader.close();

		return resultStringBuffer;
	}

	@Override
	public StringBuffer readFromTxtFile(String filePath) throws IOException {
		BufferedReader in = new BufferedReader(new FileReader(filePath));
		StringBuffer data = new StringBuffer();
		int c = 0;
		while ((c = in.read()) != -1) {
			data.append((char) c);
		}
		in.close();
		return data;
	}

}